<template>
  <div class="refund-export-report">
    <!-- 第一步：查询结算主数据 -->
    <div class="card mb-4" v-if="currentStep === 1">
      <div class="card-header">
        <h5 class="card-title mb-0">
          <i class="bi bi-search"></i> 查询结算主数据
        </h5>
      </div>
      <div class="card-body">
        <form @submit.prevent="searchAcctData" class="row g-3">
          <div class="col-md-4">
            <label for="startDate" class="form-label">开始日期</label>
            <input 
              type="date" 
              class="form-control" 
              id="startDate" 
              v-model="searchForm.startDate"
              required
            >
          </div>
          <div class="col-md-4">
            <label for="endDate" class="form-label">结束日期</label>
            <input 
              type="date" 
              class="form-control" 
              id="endDate" 
              v-model="searchForm.endDate"
              required
            >
          </div>
          <div class="col-md-4">
            <label class="form-label">&nbsp;</label>
            <div>
              <button type="submit" class="btn btn-primary" :disabled="loading">
                <span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
                <i v-else class="bi bi-search me-2"></i>
                查询
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>

    <!-- 结算主数据列表 -->
    <div class="card mb-4" v-if="currentStep === 1 && (acctData.length > 0 || totalCount > 0)">
      <div class="card-header">
        <h5 class="card-title mb-0">
          <i class="bi bi-table"></i> 结算主数据列表
        </h5>
      </div>
      <div class="card-body">
        <!-- 分页信息和控制 -->
        <div v-if="totalCount > 0" class="row mb-3">
          <div class="col-md-6">
            <div class="d-flex align-items-center">
              <div class="text-muted">
                <i class="bi bi-info-circle me-1"></i>
                共 {{ totalCount }} 条记录，
                第 {{ currentPage }} 页，共 {{ Math.ceil(totalCount / pageSize) }} 页
              </div>
            </div>
          </div>
          <div class="col-md-6">
            <div class="d-flex align-items-center justify-content-md-end flex-wrap">
              <!-- 每页显示条数选择 -->
              <div class="d-flex align-items-center me-3 mb-2 mb-md-0">
                <span class="text-muted me-2">
                  <i class="bi bi-list-ul me-1"></i>
                  每页显示
                </span>
                <select 
                  class="form-select form-select-sm" 
                  style="width: auto; min-width: 80px;"
                  :value="pageSize"
                  @change="handlePageSizeChange(parseInt($event.target.value))"
                >
                  <option value="10">10 条</option>
                  <option value="20">20 条</option>
                  <option value="50">50 条</option>
                  <option value="100">100 条</option>
                </select>
              </div>
              
              <!-- 页面跳转 -->
              <div class="d-flex align-items-center mb-2 mb-md-0" v-if="Math.ceil(totalCount / pageSize) > 1">
                <span class="text-muted me-2">
                  <i class="bi bi-skip-end me-1"></i>
                  跳转到
                </span>
                <input 
                  type="number" 
                  class="form-control form-control-sm me-2" 
                  style="width: 70px;"
                  v-model="jumpToPage"
                  :placeholder="'1-' + Math.ceil(totalCount / pageSize)"
                  min="1"
                  :max="Math.ceil(totalCount / pageSize)"
                  @keyup.enter="handleJumpToPage"
                >
                <span class="text-muted me-2">页</span>
                <button 
                  class="btn btn-outline-primary btn-sm" 
                  @click="handleJumpToPage"
                  :disabled="!jumpToPage"
                  title="跳转到指定页面"
                >
                  <i class="bi bi-arrow-right"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 分页导航 -->
        <div v-if="Math.ceil(totalCount / pageSize) > 1" class="d-flex justify-content-center mb-3">
          <nav aria-label="分页导航">
            <ul class="pagination mb-0">
              <!-- 首页 -->
              <li class="page-item" :class="{ disabled: currentPage === 1 }">
                <button 
                  class="page-link" 
                  @click="handlePageChange(1)" 
                  :disabled="currentPage === 1"
                  title="首页"
                >
                  <i class="bi bi-chevron-double-left"></i>
                </button>
              </li>
              
              <!-- 上一页 -->
              <li class="page-item" :class="{ disabled: currentPage === 1 }">
                <button 
                  class="page-link" 
                  @click="handlePageChange(currentPage - 1)" 
                  :disabled="currentPage === 1"
                  title="上一页"
                >
                  <i class="bi bi-chevron-left"></i>
                </button>
              </li>
              
              <!-- 页码 -->
              <li v-for="page in getPageNumbers()" :key="page" class="page-item" :class="{ active: page === currentPage }">
                <button class="page-link" @click="handlePageChange(page)" :title="'第' + page + '页'">{{ page }}</button>
              </li>
              
              <!-- 下一页 -->
              <li class="page-item" :class="{ disabled: currentPage === Math.ceil(totalCount / pageSize) }">
                <button 
                  class="page-link" 
                  @click="handlePageChange(currentPage + 1)" 
                  :disabled="currentPage === Math.ceil(totalCount / pageSize)"
                  title="下一页"
                >
                  <i class="bi bi-chevron-right"></i>
                </button>
              </li>
              
              <!-- 末页 -->
              <li class="page-item" :class="{ disabled: currentPage === Math.ceil(totalCount / pageSize) }">
                <button 
                  class="page-link" 
                  @click="handlePageChange(Math.ceil(totalCount / pageSize))" 
                  :disabled="currentPage === Math.ceil(totalCount / pageSize)"
                  title="末页"
                >
                  <i class="bi bi-chevron-double-right"></i>
                </button>
              </li>
            </ul>
          </nav>
        </div>

        <!-- 批量操作工具栏 -->
        <div class="d-flex justify-content-between align-items-center mb-3" v-if="acctData.length > 0">
          <div class="d-flex align-items-center">
            <div class="form-check me-3">
              <input 
                class="form-check-input" 
                type="checkbox" 
                id="selectAllCheckbox"
                v-model="selectAll"
                @change="handleSelectAll"
              >
              <label class="form-check-label" for="selectAllCheckbox">
                全选
              </label>
            </div>
            <span class="text-muted">
              已选择 {{ selectedAcctIds.size }} 项
            </span>
          </div>
          <div>
            <button 
              class="btn btn-success" 
              @click="batchExportToExcel" 
              :disabled="selectedAcctIds.size === 0 || batchExporting"
            >
              <span v-if="batchExporting" class="spinner-border spinner-border-sm me-2"></span>
              <i v-else class="bi bi-download me-2"></i>
              批量导出Excel ({{ selectedAcctIds.size }})
            </button>
          </div>
        </div>

        <div class="table-responsive">
          <table class="table table-striped table-hover">
            <thead class="table-dark">
              <tr>
                <th style="width: 50px;">
                  <div class="form-check">
                    <input 
                      class="form-check-input" 
                      type="checkbox" 
                      v-model="selectAll"
                      @change="handleSelectAll"
                    >
                  </div>
                </th>
                <th>结算ID</th>
                <th>录入时间</th>
                <th>操作员</th>
                <th>用户名</th>
                <th>本单总金额</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in acctData" :key="item.acctId">
                <td>
                  <div class="form-check">
                    <input 
                      class="form-check-input" 
                      type="checkbox" 
                      :value="item.acctId"
                      :checked="selectedAcctIds.has(item.acctId)"
                      @change="handleItemSelect(item.acctId, $event.target.checked)"
                    >
                  </div>
                </td>
                <td>{{ item.acctId }}</td>
                <td>{{ formatDateTime(item.inputDate) }}</td>
                <td>{{ item.fullName || '-' }}</td>
                <td>{{ item.username }}</td>
                <td class="text-end">
                  <span class="badge bg-success">¥{{ parseFloat(item.refundBalanceSum || 0).toFixed(2) }}</span>
                </td>
                <td>
                  <button 
                    class="btn btn-primary btn-sm" 
                    @click="selectAcctData(item)"
                    :disabled="loadingDetails"
                  >
                    <span v-if="loadingDetails && selectedAcctId === item.acctId" class="spinner-border spinner-border-sm me-2"></span>
                    <i v-else class="bi bi-eye me-2"></i>
                    查看详情
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 第二步：显示退款明细数据 -->
    <div class="card" v-if="currentStep === 2">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">
          <i class="bi bi-file-earmark-spreadsheet"></i> 退款申请财务报表
        </h5>
        <div>
          <button class="btn btn-outline-secondary me-2" @click="goBack">
            <i class="bi bi-arrow-left me-2"></i>
            返回
          </button>
          <button class="btn btn-success" @click="exportToExcel" :disabled="exporting">
            <span v-if="exporting" class="spinner-border spinner-border-sm me-2"></span>
            <i v-else class="bi bi-download me-2"></i>
            导出Excel
          </button>
        </div>
      </div>
      <div class="card-body">
        <!-- 结算信息摘要 -->
        <div class="alert alert-info mb-4">
          <h6><i class="bi bi-info-circle me-2"></i>结算信息</h6>
          <div class="row">
            <div class="col-md-3"><strong>结算ID：</strong>{{ selectedAcct.acctId }}</div>
            <div class="col-md-3"><strong>录入时间：</strong>{{ formatDateTime(selectedAcct.inputDate) }}</div>
            <div class="col-md-3"><strong>操作员：</strong>{{ selectedAcct.fullName || selectedAcct.username }}</div>
            <div class="col-md-3"><strong>总金额：</strong>¥{{ parseFloat(selectedAcct.refundBalanceSum || 0).toFixed(2) }}</div>
          </div>
        </div>

        <!-- 退款明细表格 -->
        <div class="table-responsive" v-if="refundDetails.length > 0">
          <table class="table table-striped table-hover table-sm">
            <thead class="table-dark">
              <tr>
                <th v-for="column in tableColumns" :key="column.field">{{ column.label }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in refundDetails" :key="item.id">
                <td v-for="column in tableColumns" :key="column.field">
                  {{ getFieldValue(item, column.field) }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 空数据提示 -->
        <div v-else-if="!loadingDetails" class="text-center py-5">
          <i class="bi bi-inbox display-1 text-muted"></i>
          <p class="text-muted mt-3">暂无退款明细数据</p>
        </div>

        <!-- 加载中 -->
        <div v-if="loadingDetails" class="text-center py-5">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
          </div>
          <p class="text-muted mt-3">正在加载退款明细数据...</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import api from '@/utils/api'
import * as XLSX from 'xlsx'

// 响应式数据
const loading = ref(false)
const loadingDetails = ref(false)
const exporting = ref(false)
const batchExporting = ref(false)
const currentStep = ref(1)
const selectedAcctId = ref('')
const selectedAcctIds = ref(new Set())
const selectAll = ref(false)

// 分页相关
const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const jumpToPage = ref('')

// 搜索表单
const searchForm = ref({
  startDate: '',
  endDate: ''
})

// 数据
const acctData = ref([])
const selectedAcct = ref({})
const refundDetails = ref([])
const batchRefundDetails = ref([])

// 表格列定义（基于Excel模板）
const tableColumns = ref([
  { field: 'bankCardHolder', label: '申请人' },
  { field: 'phoneNumber', label: '手机' },
  { field: 'publicAgentRelation', label: '关系' },
  { field: 'refundTypeName', label: '退款类型' },
  { field: 'refundBankCardNo', label: '银行卡号' },
  { field: 'bankCardHolder', label: '银行卡持有人' },
  { field: 'refundBankOpenName', label: '开户行'},
    { field: 'refundBankCity', label: '城市' },
  { field: 'refundBankName', label: '银行名称' },
  { field: 'patName', label: '患者姓名' },
  { field: 'idNumber', label: '身份证号' },
  { field: 'patientId', label: '患者ID' },
  { field: 'refundAmount', label: '申请退款金额' },
  { field: 'refundBalance', label: '实际退款金额' },
  { field: 'auditUserName', label: '审核人' },
  { field: 'auditResult', label: '审核结果' },
  { field: 'inputDate', label: '申请日期日期' },
  { field: 'auditDate', label: '审核日期' }
])

// 方法
const searchAcctData = async (resetPage = true) => {
  loading.value = true
  
  try {
    // 如果是重新搜索，重置到第一页
    if (resetPage) {
      currentPage.value = 1
    }
    
    // 处理日期范围，确保结束日期包含当天的所有数据
    let startDateParam = searchForm.value.startDate
    let endDateParam = searchForm.value.endDate
    
    // 如果有结束日期，将其设置为当天的23:59:59
    if (endDateParam) {
      endDateParam = endDateParam + 'T23:59:59'
    }
    
    // 如果有开始日期，将其设置为当天的00:00:00
    if (startDateParam) {
      startDateParam = startDateParam + 'T00:00:00'
    }
    
    const params = {
      startDate: startDateParam,
      endDate: endDateParam,
      pageNumber: currentPage.value,
      pageSize: pageSize.value
    }
    
    const response = await api.get('/api/RefundAcct/paged', { params })
    
    if (response.data) {
      acctData.value = response.data.items || []
      totalCount.value = response.data.totalCount || 0
      
      if (acctData.value.length === 0 && totalCount.value === 0) {
        showToast('未找到符合条件的结算数据', 'warning')
      }
    }
  } catch (error) {
    console.error('查询结算数据失败:', error)
    showToast('查询结算数据失败，请重试', 'error')
    acctData.value = []
    totalCount.value = 0
  } finally {
    loading.value = false
    // 查询完成后更新全选状态
    updateSelectAllStatus()
  }
}

// 分页处理
const handlePageChange = (page) => {
  if (page < 1 || page > Math.ceil(totalCount.value / pageSize.value)) {
    return
  }
  currentPage.value = page
  searchAcctData(false) // 不重置页码
  // 分页变化时更新全选状态
  updateSelectAllStatus()
}

// 跳转到指定页面
const handleJumpToPage = () => {
  const page = parseInt(jumpToPage.value)
  const totalPages = Math.ceil(totalCount.value / pageSize.value)
  
  if (isNaN(page) || page < 1 || page > totalPages) {
    showToast('请输入有效的页码（1-' + totalPages + '）', 'warning')
    jumpToPage.value = ''
    return
  }
  
  jumpToPage.value = ''
  handlePageChange(page)
}

// 处理每页显示条数变化
const handlePageSizeChange = (newPageSize) => {
  pageSize.value = newPageSize
  currentPage.value = 1 // 重置到第一页
  jumpToPage.value = ''
  searchAcctData(false) // 不重置页码，因为已经手动重置了
  // 分页变化时更新全选状态
  updateSelectAllStatus()
}

// 更新全选状态
const updateSelectAllStatus = () => {
  if (acctData.value.length === 0) {
    selectAll.value = false
    return
  }
  
  const currentPageIds = acctData.value.map(item => item.acctId)
  const allCurrentPageSelected = currentPageIds.every(id => selectedAcctIds.value.has(id))
  selectAll.value = allCurrentPageSelected
}

// 获取页码数组
const getPageNumbers = () => {
  const totalPages = Math.ceil(totalCount.value / pageSize.value)
  const pages = []
  const maxVisiblePages = 5
  
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2))
  let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1)
  
  // 调整起始页
  if (endPage - startPage + 1 < maxVisiblePages) {
    startPage = Math.max(1, endPage - maxVisiblePages + 1)
  }
  
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }
  
  return pages
}

const selectAcctData = async (acct) => {
  selectedAcct.value = acct
  selectedAcctId.value = acct.acctId
  loadingDetails.value = true
  
  try {
    // 通过acct_id查询lzfy_refund_master数据
    const response = await api.get(`/api/Refund/by-acct-id/${acct.acctId}`)
    
    if (response.data) {
      // 检查响应数据结构，如果有data字段则使用data字段的内容
      const actualData = response.data.data || response.data
      refundDetails.value = Array.isArray(actualData) ? actualData : [actualData]
      currentStep.value = 2
    }
  } catch (error) {
    console.error('查询退款明细失败:', error)
    showToast('查询退款明细失败，请重试', 'error')
    refundDetails.value = []
  } finally {
    loadingDetails.value = false
  }
}

const goBack = () => {
  currentStep.value = 1
  selectedAcct.value = {}
  refundDetails.value = []
  selectedAcctId.value = ''
  // 保持分页状态，不重置分页数据
}

// 多选相关方法
const handleSelectAll = () => {
  if (selectAll.value) {
    // 全选当前页的所有项目
    acctData.value.forEach(item => {
      selectedAcctIds.value.add(item.acctId)
    })
  } else {
    // 取消选择当前页的所有项目
    acctData.value.forEach(item => {
      selectedAcctIds.value.delete(item.acctId)
    })
  }
}

const handleItemSelect = (acctId, checked) => {
  if (checked) {
    selectedAcctIds.value.add(acctId)
  } else {
    selectedAcctIds.value.delete(acctId)
    selectAll.value = false
  }
  
  // 检查是否当前页全部选中
  const currentPageIds = acctData.value.map(item => item.acctId)
  const allCurrentPageSelected = currentPageIds.every(id => selectedAcctIds.value.has(id))
  selectAll.value = allCurrentPageSelected && currentPageIds.length > 0
}

// 批量导出Excel
const batchExportToExcel = async () => {
  if (selectedAcctIds.value.size === 0) {
    showToast('请先选择要导出的结算数据', 'warning')
    return
  }
  
  batchExporting.value = true
  batchRefundDetails.value = []
  
  try {
    // 批量获取所有选中结算的退款明细
    const promises = Array.from(selectedAcctIds.value).map(async (acctId) => {
      try {
        const response = await api.get(`/api/Refund/by-acct-id/${acctId}`)
        if (response.data) {
          const actualData = response.data.data || response.data
          const details = Array.isArray(actualData) ? actualData : [actualData]
          return details.map(detail => ({
            ...detail,
            acctId: acctId // 添加结算ID用于区分
          }))
        }
        return []
      } catch (error) {
        console.error(`获取结算${acctId}的退款明细失败:`, error)
        return []
      }
    })
    
    const results = await Promise.all(promises)
    batchRefundDetails.value = results.flat()
    
    if (batchRefundDetails.value.length === 0) {
      showToast('选中的结算数据中没有找到退款明细', 'warning')
      return
    }
    
    // 导出合并的Excel
    await exportBatchToExcel()
    
  } catch (error) {
    console.error('批量导出失败:', error)
    showToast('批量导出失败，请重试', 'error')
  } finally {
    batchExporting.value = false
  }
}

// 批量导出Excel实现
const exportBatchToExcel = async () => {
  try {
    // 创建工作簿
    const workbook = new ExcelJS.Workbook()
    const worksheet = workbook.addWorksheet('批量退费明细报表')
    
    // 使用tableColumns的列数来确定合并范围
    const totalColumns = tableColumns.value.length
    
    // 添加表头（合并单元格）
    const headerRow = worksheet.addRow(['柳州市妇幼保健院批量退费明细报表'])
    worksheet.mergeCells(1, 1, 1, totalColumns)
    
    // 设置表头样式
    const headerCell = worksheet.getCell(1, 1)
    headerCell.font = {
      name: '宋体',
      size: 22,
      bold: true
    }
    headerCell.alignment = {
      horizontal: 'center',
      vertical: 'middle'
    }
    headerCell.border = {
      top: { style: 'thin' },
      left: { style: 'thin' },
      bottom: { style: 'thin' },
      right: { style: 'thin' }
    }
    
    // 设置表头行高
    headerRow.height = 35
    
    // 使用tableColumns定义的列标题
    const columnHeaders = tableColumns.value.map(col => col.label)
    
    // 添加列标题
    const columnRow = worksheet.addRow(columnHeaders)
    columnRow.height = 25
    
    // 设置列标题样式
    columnRow.eachCell((cell) => {
      cell.font = {
        name: '宋体',
        size: 12,
        bold: true
      }
      cell.alignment = {
        horizontal: 'center',
        vertical: 'middle'
      }
      cell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFD9D9D9' }
      }
      cell.border = {
        top: { style: 'thin' },
        left: { style: 'thin' },
        bottom: { style: 'thin' },
        right: { style: 'thin' }
      }
    })
    
    // 准备数据并计算汇总
    let totalRefundAmount = 0
    let totalRefundBalance = 0
    
    const exportData = batchRefundDetails.value.map(item => {
      const refundAmount = parseFloat(item.refundAmount || 0)
      const refundBalance = parseFloat(item.refundBalance || 0)
      
      totalRefundAmount += refundAmount
      totalRefundBalance += refundBalance
      
      // 使用tableColumns配置来生成行数据
      return tableColumns.value.map(column => {
        return getFieldValue(item, column.field)
      })
    })
    
    // 添加汇总行 - 根据tableColumns动态生成
    const summaryRowData = tableColumns.value.map((column, index) => {
      if (column.field === 'refundAmount') {
        return totalRefundAmount
      } else if (column.field === 'refundBalance') {
        return totalRefundBalance
      } else if (index === Math.floor(tableColumns.value.length / 2)) {
        // 在中间位置显示"合计:"
        return '合计:'
      } else {
        return ''
      }
    })
    exportData.push(summaryRowData)
    
    // 添加数据行
    exportData.forEach((rowData, index) => {
      const row = worksheet.addRow(rowData)
      row.height = 20
      
      const isLastRow = index === exportData.length - 1
      
      row.eachCell((cell, colNumber) => {
        cell.font = {
          name: '宋体',
          size: 10,
          bold: isLastRow
        }
        
        // 设置数据类型和格式
        if (!isLastRow) {
          const columnField = tableColumns.value[colNumber - 1]?.field
          
          // 根据字段类型设置格式
          if (['idNumber', 'patientId', 'refundBankCardNo', 'phoneNumber'].includes(columnField)) {
            // 设置为文本格式，避免科学计数法
            cell.value = String(cell.value || '')
            cell.numFmt = '@' // 文本格式
          } else if (['refundAmount', 'refundBalance'].includes(columnField)) {
            // 设置为数值格式
            const numValue = parseFloat(cell.value || 0)
            cell.value = numValue
            cell.numFmt = '#,##0.00' // 数字格式，保留两位小数
          }
        }
        
        // 设置对齐方式
        if (isLastRow) {
          cell.alignment = { horizontal: 'center', vertical: 'middle' }
        } else {
          const columnField = tableColumns.value[colNumber - 1]?.field
          // 金额列右对齐，其他左对齐
          cell.alignment = {
            horizontal: ['refundAmount', 'refundBalance'].includes(columnField) ? 'right' : 'left',
            vertical: 'middle'
          }
        }
        
        // 汇总行背景色
        if (isLastRow) {
          cell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFFFFF99' }
          }
        }
        
        cell.border = {
          top: { style: 'thin' },
          left: { style: 'thin' },
          bottom: { style: 'thin' },
          right: { style: 'thin' }
        }
      })
    })
    
    // 根据列数动态设置列宽
    tableColumns.value.forEach((column, index) => {
      let width = 12 // 默认宽度
      
      // 根据字段类型设置不同的列宽
      switch (column.field) {
        case 'idNumber':
        case 'refundBankCardNo':
          width = 20
          break
        case 'refundBankOpenName':
        case 'refundBankName':
          width = 16
          break
        case 'inputDate':
        case 'auditDate':
          width = 18
          break
        case 'refundAmount':
        case 'refundBalance':
          width = 14
          break
        case 'phoneNumber':
          width = 13
          break
        default:
          width = 12
      }
      
      worksheet.getColumn(index + 1).width = width
    })
    
    // 生成文件
    const buffer = await workbook.xlsx.writeBuffer()
    const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    
    // 下载文件
    const now = new Date()
    const fileName = `柳州市妇幼保健院批量退费明细报表_导出时间_${now.toISOString().split('T')[0]}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}.xlsx`
    
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = fileName
    a.click()
    window.URL.revokeObjectURL(url)
    
    showToast(`成功导出 ${batchRefundDetails.value.length} 条退费明细数据`, 'success')
    
    // 清空选择
    clearSelection()
    
  } catch (error) {
    console.error('导出Excel失败:', error)
    showToast('导出Excel失败，请重试', 'error')
  }
}

// 清空选择
const clearSelection = () => {
  selectedAcctIds.value.clear()
  selectAll.value = false
  batchRefundDetails.value = []
}

// 获取退费状态文本
const getRefundStatusText = (status) => {
  const statusMap = {
    0: '待处理',
    1: '已通过',
    2: '已拒绝',
    3: '已完成'
  }
  return statusMap[status] || '未知状态'
}

const getFieldValue = (item, field) => {
  // 特殊字段处理
  switch (field) {
    case 'phoneNumber':
      return item.refundTypeName === '本人退款' ? (item.phoneNumber || '-') : (item.publicAgentPhoneNumber || '-')
    case 'refundBankCity':
      return item.refundBankCity || item.publicAgentRefundBankCity || '-'
    case 'publicAgentRelation':
      return item.publicAgentRelation || '-'
    case 'refundBankCardNo':
      return item.refundTypeName === '本人退款' ? (item.refundBankCardNo || '-') : (item.publicAgentRefundBankCardNo || '-')
    case 'bankCardHolder':
      return item.refundTypeName === '本人退款' ? (item.patName || '-') : (item.publicAgentName || '-')
    case 'patName':
      return item.patName || '-'
    case 'idNumber':
       return item.idNumber || '-'
    case 'refundBankName':
      return item.refundTypeName === '本人退款' ? (item.refundBankName || '-') : (item.publicAgentRefundBankName || '-')
    case 'inputDate':
    case 'auditDate':
      return formatDateTime(item[field])
    case 'refundAmount':
    case 'refundBalance':
      return parseFloat(item[field] || 0).toFixed(2)
    case 'auditResult':
      const statusMap = {
        '0': '待审核',
        '1': '审核通过',
        '2': '审核失败'
      }
      return statusMap[item[field]] || '未知'
    default:
      return item[field] || '-'
  }
}

// 导入ExcelJS
import ExcelJS from 'exceljs'

const exportToExcel = async () => {
  exporting.value = true
  
  try {
    // 创建工作簿
    const workbook = new ExcelJS.Workbook()
    const worksheet = workbook.addWorksheet('退款申请财务报表')
    
    // 添加表头（合并单元格）
    const headerRow = worksheet.addRow(['柳州市妇幼保健院线上申请退费财务报表'])
    worksheet.mergeCells(1, 1, 1, tableColumns.value.length)
    
    // 设置表头样式
    const headerCell = worksheet.getCell(1, 1)
    headerCell.font = {
      name: '宋体',
      size: 22,
      bold: true
    }
    headerCell.alignment = {
      horizontal: 'center',
      vertical: 'middle'
    }
    headerCell.border = {
      top: { style: 'thin' },
      left: { style: 'thin' },
      bottom: { style: 'thin' },
      right: { style: 'thin' }
    }
    
    // 设置表头行高
    headerRow.height = 35
    
    // 添加列标题
    const columnRow = worksheet.addRow(tableColumns.value.map(col => col.label))
    columnRow.height = 25
    
    // 设置列标题样式
    columnRow.eachCell((cell) => {
      cell.font = {
        name: '宋体',
        size: 12,
        bold: true
      }
      cell.alignment = {
        horizontal: 'center',
        vertical: 'middle'
      }
      cell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFD9D9D9' }
      }
      cell.border = {
        top: { style: 'thin' },
        left: { style: 'thin' },
        bottom: { style: 'thin' },
        right: { style: 'thin' }
      }
    })
    
    // 准备数据
    const exportData = refundDetails.value.map(item => {
      return tableColumns.value.map(column => getFieldValue(item, column.field))
    })
    
    // 计算汇总
    const totalRefundAmount = refundDetails.value.reduce((sum, item) => {
      return sum + (parseFloat(item.refundAmount) || 0)
    }, 0)
    
    const totalRefundBalance = refundDetails.value.reduce((sum, item) => {
      return sum + (parseFloat(item.refundBalance) || 0)
    }, 0)
    
    // 添加汇总行
    const summaryRowData = tableColumns.value.map(column => {
      if (column.field === 'refundAmount') {
        return `${totalRefundAmount.toFixed(2)}`
      } else if (column.field === 'refundBalance') {
        return `${totalRefundBalance.toFixed(2)}`
      } else {
        return ''
      }
    })
    
    exportData.push(summaryRowData)
    
    // 添加数据行
    exportData.forEach((rowData, index) => {
      const row = worksheet.addRow(rowData)
      row.height = 20
      
      const isLastRow = index === exportData.length - 1
      
      row.eachCell((cell, colNumber) => {
        const column = tableColumns.value[colNumber - 1]
        
        cell.font = {
          name: '宋体',
          size: 10,
          bold: isLastRow
        }
        
        // 设置数据类型和格式
        if (!isLastRow && column) {
          switch (column.field) {
            case 'phoneNumber': // B列 - 手机号
            case 'refundBankCardNo': // E列 - 银行卡号
            case 'idNumber': // J列 - 身份证号
              // 设置为文本格式，避免科学计数法
              cell.value = String(cell.value || '')
              cell.numFmt = '@' // 文本格式
              break
            case 'refundAmount': // L列 - 申请退款金额
            case 'refundBalance': // M列 - 实际退款金额
              // 设置为数值格式
              const numValue = parseFloat(cell.value || 0)
              cell.value = numValue
              cell.numFmt = '#,##0.00' // 数字格式，保留两位小数
              break
            case 'patientId': // 患者ID也可能需要文本格式
              cell.value = String(cell.value || '')
              cell.numFmt = '@'
              break
          }
        }
        
        // 设置对齐方式
        if (isLastRow) {
          cell.alignment = { horizontal: 'center', vertical: 'middle' }
        } else {
          // 金额列右对齐，其他左对齐
          cell.alignment = {
            horizontal: (column && (column.field === 'refundAmount' || column.field === 'refundBalance')) ? 'right' : 'left',
            vertical: 'middle'
          }
        }
        
        // 汇总行背景色
        if (isLastRow) {
          cell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFFFFF99' }
          }
        }
        
        cell.border = {
          top: { style: 'thin' },
          left: { style: 'thin' },
          bottom: { style: 'thin' },
          right: { style: 'thin' }
        }
      })
    })
    
    // 设置列宽
    tableColumns.value.forEach((col, index) => {
      let width = 15
      
      // 根据列内容调整宽度
      switch (col.field) {
        case 'phoneNumber': // B列 - 手机号
          width = 12
          break
        case 'refundBankCardNo': // E列 - 银行卡号
          width = 20
          break
        case 'idNumber': // J列 - 身份证号
          width = 18 // 增加20%宽度
          break
        case 'refundAmount': // L列 - 申请退款金额
        case 'refundBalance': // M列 - 实际退款金额
          width = 12
          break
        case 'patName': // 患者姓名
        case 'bankCardHolder': // 银行卡持有人
          width = 10
          break
        case 'refundBankName': // 银行名称
        case 'refundBankOpenName': // 开户行
          width = 16
          break
      }
      
      worksheet.getColumn(index + 1).width = width
    })
    
    // 生成文件
    const buffer = await workbook.xlsx.writeBuffer()
    const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    
    // 下载文件
    const fileName = `柳州市妇幼保健院线上申请退费财务报表_制表人:${selectedAcct.value.fullName}_表单ID:${selectedAcct.value.acctId}_制表时间:${selectedAcct.value.inputDate.split('T')[0]}_导出时间_${new Date().toISOString().split('T')[0]}.xlsx`
    
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = fileName
    a.click()
    window.URL.revokeObjectURL(url)
    
    showToast('柳州市妇幼保健院线上申请退费财务报表导出成功', 'success')
  } catch (error) {
    console.error('导出Excel失败:', error)
    showToast('导出Excel失败，请重试', 'error')
  } finally {
    exporting.value = false
  }
}

const formatDateTime = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const showToast = (message, type = 'info') => {
  const alertClass = {
    'success': 'alert-success',
    'error': 'alert-danger',
    'warning': 'alert-warning',
    'info': 'alert-info'
  }[type] || 'alert-info'
  
  const toast = document.createElement('div')
  toast.className = `alert ${alertClass} alert-dismissible fade show position-fixed`
  toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;'
  toast.innerHTML = `
    ${message}
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  `
  
  document.body.appendChild(toast)
  
  setTimeout(() => {
    if (toast.parentNode) {
      toast.parentNode.removeChild(toast)
    }
  }, 5000)
}

// 暴露组件方法
defineExpose({
  handleSelectAll,
  handleItemSelect,
  batchExportToExcel,
  clearSelection,
  updateSelectAllStatus
})

// 生命周期
onMounted(() => {
  // 设置默认日期范围（最近30天）
  const today = new Date()
  // 确保使用本地时间而不是UTC时间
  const endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate())
  const startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 30)
  
  // 格式化为YYYY-MM-DD格式
  const formatDate = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }
  
  searchForm.value.endDate = formatDate(endDate)
  searchForm.value.startDate = formatDate(startDate)
})
</script>

<style scoped>
.refund-export-report {
  padding: 0;
}

.table th {
  background-color: #495057;
  color: white;
  border-color: #495057;
}

.table-hover tbody tr:hover {
  background-color: rgba(0, 123, 255, 0.1);
}

.badge {
  font-size: 0.75em;
}

.card {
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  border: 1px solid rgba(0, 0, 0, 0.125);
}

.alert {
  border-radius: 0.375rem;
}

.table-sm th,
.table-sm td {
  padding: 0.5rem;
  font-size: 0.875rem;
}
</style>